package com.hbzhit.modules.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbzhit.common.utils.CacheUtils;
import com.hbzhit.common.utils.PageUtils;
import com.hbzhit.common.utils.Query;
import com.hbzhit.modules.sys.dao.SysLogDao;
import com.hbzhit.modules.sys.entity.SysLogEntity;
import com.hbzhit.modules.sys.entity.SysUserEntity;
import com.hbzhit.modules.sys.service.SysLogService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;


@Service("sysLogService")
public class SysLogServiceImpl extends ServiceImpl<SysLogDao, SysLogEntity> implements SysLogService {

    @Override
    public PageUtils<SysLogEntity> queryPage(Map<String, Object> params) {
        String key = (String)params.get("key");

        IPage<SysLogEntity> page = this.page(
            new Query<SysLogEntity>().getPage(params),
            new QueryWrapper<SysLogEntity>().lambda()
                    .and(StrUtil.isNotBlank(key), wrapper -> wrapper
                            .like(SysLogEntity::getUsername, key)
                            .or()
                            .like(SysLogEntity::getOperation, key)
                    )
                    .orderByDesc(SysLogEntity::getCreateDate)
        );

        return new PageUtils<>(page);
    }

    @Override
    public boolean saveLog(Long userId, String operation, String ip) {
        SysUserEntity user = CacheUtils.getUserCache(userId);
        SysLogEntity sysLog = new SysLogEntity();
        sysLog.setOperation(operation);
        sysLog.setUserId(userId);
        sysLog.setUsername(user.getUsername());
        sysLog.setIp(ip);
        sysLog.setCreateDate(new Date());
        sysLog.setTime(0L);
        this.save(sysLog);

        return true;
    }
}
